package dice.sinanya.db.monsterlist;

import dice.sinanya.db.tools.DbUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;

import static dice.sinanya.system.NpcListCache.MONSTER_LIST;
import static dice.sinanya.tools.makedata.MakeProperties.makeProMapToStr;
import static dice.sinanya.tools.makedata.MakeProperties.makeProStrToMap;

public class InsertMonsterList {
    private static final Logger log = LogManager.getLogger(InsertMonsterList.class.getName());


    public InsertMonsterList() {
        //        初始化时不需要参数
    }

    public void insertMonsterList(String groupId, String name, String properties) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "REPLACE INTO test.monsterList(" +
                    "groupId, name,properties) VALUES(?,?,?)";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.setString(2, name);
                ps.setString(3, properties);
                ps.executeUpdate();
            }
            HashMap<String, HashMap<String, Integer>> MONSTER_TMP = MONSTER_LIST.getOrDefault(groupId, new HashMap<>());
            MONSTER_TMP.put(name, makeProStrToMap(properties));
            MONSTER_LIST.put(groupId, MONSTER_TMP);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void insertMonsterList(String groupId, String name, HashMap<String, Integer> properties) {
        insertMonsterList(groupId, name, makeProMapToStr(properties));
    }

    public void deleteMonsterList(String groupId, String name) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "delete from test.monsterList where groupId=? and name=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.setString(2, name);
                ps.executeUpdate();
            }
            HashMap<String, HashMap<String, Integer>> MONSTER_TMP = MONSTER_LIST.getOrDefault(groupId, new HashMap<>());
            MONSTER_TMP.remove(name);
            MONSTER_LIST.put(groupId, MONSTER_TMP);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void deleteMonsterListByGroup(String groupId) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "delete from test.monsterList where groupId=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.executeUpdate();
            }
            MONSTER_LIST.remove(groupId);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
}

